package org.one.afternoon.controller;

import org.one.afternoon.common.Result;
import org.one.afternoon.domain.User;
import org.one.afternoon.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.List;


/**
 * 响应用户
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;


    @CrossOrigin // 跨域访问
    @GetMapping("/users")
    public Result<List<User>> findAllUser() {
        return Result.success(userService.findAll());
    }


    //复合查询
    @CrossOrigin
    @PostMapping("/query")
    @ResponseBody
    public Result<List<User>> queryUser(@RequestBody User user) {
        return Result.success(userService.queryOne(user));
    }

    @CrossOrigin
    @PostMapping("/insert")
    @ResponseBody
    public Result<String> insert(@RequestBody User user) {
        boolean save = userService.insert(user);
        if (save) {
            return Result.success("成功添加用户");
        }
        return Result.error("添加用户失败");
    }

    @CrossOrigin
    @PostMapping("/delete")
    @ResponseBody
    public Result<String> delete(@RequestParam Integer index) {
        userService.deleteById(index);
        return Result.success("删除成功");
    }


    @CrossOrigin
    @PostMapping("/update")
    @ResponseBody
    public Result<String> update(@RequestBody User user) {
        boolean update = userService.update(user);
        if (update) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }


    @CrossOrigin
    @PostMapping("/login")
    @ResponseBody
    public Result<String> login(@RequestBody User user) throws NoSuchAlgorithmException {
        boolean login = userService.login(user);
        if (login) {
            return Result.success("登录成功");
        } else {
            return Result.error("登录失败");
        }
    }

    @CrossOrigin
    @PostMapping("/logout")
    @ResponseBody
    public Result<String> logout(@RequestParam String username) {
        boolean logout = userService.logout(username);
        if (logout) {
            return Result.success("登出成功");
        } else {
            return Result.error("登出失败");
        }
    }
}
